package com.milepost.workflow.user.ctrl;

import com.milepost.messagepush.common.constant.MilepostConstant;
import com.milepost.messagepush.common.enums.DsKeyEnum;
import com.milepost.messagepush.config.dynamicDs.DataSourceContextHolder;
import com.milepost.messagepush.response.Response;
import com.milepost.messagepush.response.ResponseHelper;
import com.milepost.workflow.user.entity.UsersEntity;
import com.milepost.workflow.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @author huarf
 * @Description
 * @create 2022-04-01 14:17
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserCtrl {

    //private FindByIndexNameSessionRepository<? extends Session> sessions;
    private final UserService userService;

    /**
     * 登录接口
     *
     * @param userName
     * @param httpSession
     * @return
     */
    @PostMapping("/login")
    public Response<UsersEntity> login(String userName, HttpSession httpSession) {

        Response<UsersEntity> response = null;

        try {
            DataSourceContextHolder.setDataSource(DsKeyEnum.USER.getKey());
            UsersEntity userEntity = userService.getByUserName(userName);
            //给登录接口返回数据
            response = ResponseHelper.createSuccessResponse(userEntity);
            //用户数据放入session中
            httpSession.setAttribute(MilepostConstant.USER_SESSION_KEY, userEntity);
        } catch (Exception e) {
            log.error("登录异常", e);
            response = ResponseHelper.createExceptionResponse(e);
        } finally {
            //必须清空，因为使用了SpringSession，非主库中没有SpringSession的表
            DataSourceContextHolder.clearDataSource();
        }

        return response;
    }

    @GetMapping("/logout")
    public Response<String> logout(HttpSession httpSession) {

        httpSession.removeAttribute(MilepostConstant.USER_SESSION_KEY);
        httpSession.invalidate();
        return ResponseHelper.createSuccessResponse();
    }

}
